import {Button, Card, Col, DatePicker, Form, Input, message, Modal, Radio, Row} from "antd";
import moment from "moment";
import TextArea from "antd/es/input/TextArea";
import {CalendarOutlined, FileTextOutlined, HomeOutlined, TeamOutlined, UserOutlined} from "@ant-design/icons";
import {useEffect} from "react";
import RequestUtils from "../../utils/RequestUtils";
import Apis from "../../configs/Apis";

const {Item} = Form;

const EditPersonalModal = (props) => {
    const [messageApi, contextHolder] = message.useMessage();
    const {editPersonalParam, setEditPersonalParam} = props;
    const [form] = Form.useForm();

    // 修复：安全地处理日期转换，确保是有效的moment对象
    useEffect(() => {
        if (editPersonalParam.visible) {
            // 处理日期 - 确保是有效的moment对象或null
            let birthDate = null;
            if (editPersonalParam.userInfo.userBirthDate) {
                // 检查是否已经是moment对象
                if (moment.isMoment(editPersonalParam.userInfo.userBirthDate)) {
                    birthDate = editPersonalParam.userInfo.userBirthDate;
                } else if (typeof editPersonalParam.userInfo.userBirthDate === 'string') {
                    // 从字符串解析
                    birthDate = moment(editPersonalParam.userInfo.userBirthDate);
                    // 验证日期有效性
                    if (!birthDate.isValid()) {
                        birthDate = null;
                    }
                }
            }

            form.setFieldsValue({
                ...editPersonalParam.userInfo,
                userBirthDate: birthDate
            });
        }
    }, [editPersonalParam.visible, editPersonalParam.userInfo, form]);

    const handleCancel = () => {
        setEditPersonalParam(prev => ({
            ...prev,
            visible: false
        }));
    };

    const handleSubmit = () => {
        form.validateFields()
            .then(values => {
                // 处理日期 - 确保以字符串格式保存
                const formattedValues = {
                    ...values,
                    userBirthDate: values.userBirthDate
                        ? values.userBirthDate.format('YYYY-MM-DD')
                        : ''
                };

                // 编辑用户信息
                doEditUserInfo(formattedValues);
            })
    };

    const doEditUserInfo = (params) => {
        RequestUtils.post(Apis.user.editUser, {
            userId: editPersonalParam.userInfo.userId,
            userNickname: params.userNickname,
            userGender: params.userGender,
            userBirthDate: params.userBirthDate,
            userAddress: params.userAddress,
            userIntroduction: params.userIntroduction
        }).then(res => {
            messageApi.success("编辑个人信息成功");
            handleCancel();
        }).catch(err => {
            messageApi.error("编辑个人信息失败: " + err.message);
        })
    }

    return (
        <Modal
            title={
                <div style={{display: 'flex', alignItems: 'center'}}>
                    <UserOutlined style={{color: '#1890ff', marginRight: 8}}/>
                    <span>编辑个人资料</span>
                </div>
            }
            open={editPersonalParam.visible}
            onCancel={handleCancel}
            maskClosable={false}
            width={600}
            footer={[
                <Button
                    key="cancel"
                    onClick={handleCancel}
                    style={{
                        transition: 'all 0.2s',
                        borderRadius: 6
                    }}
                >
                    取消
                </Button>,
                <Button
                    key="save"
                    type="primary"
                    onClick={handleSubmit}
                    style={{
                        transition: 'all 0.2s',
                        borderRadius: 6,
                        marginLeft: 8
                    }}
                >
                    保存修改
                </Button>
            ]}
            style={{borderRadius: 12}}
            bodyStyle={{
                padding: '24px',
                backgroundColor: '#fafafa'
            }}
            modalRender={(node) => (
                <div style={{
                    borderRadius: 12,
                    boxShadow: '0 10px 30px -5px rgba(0, 0, 0, 0.1)',
                    overflow: 'hidden'
                }}>
                    {node}
                </div>
            )}
        >

            {contextHolder}

            <Card
                bordered={false}
                style={{
                    backgroundColor: '#fff',
                    borderRadius: 8,
                    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.05)'
                }}
            >
                <Form
                    form={form}
                    layout="vertical"
                    validateMessages={{
                        required: '${label}为必填项',
                    }}
                >
                    <Row gutter={[16, 16]}>
                        {/* 用户昵称 */}
                        <Col xs={24}>
                            <Item
                                name="userNickname"
                                label={
                                    <span style={{display: 'flex', alignItems: 'center'}}>
                                        <UserOutlined style={{marginRight: 6, color: '#1890ff'}}/>
                                        用户昵称
                                    </span>
                                }
                                rules={[{required: true, message: '请输入用户昵称'}]}
                            >
                                <Input
                                    placeholder="请输入您的昵称"
                                    style={{
                                        height: 42,
                                        borderRadius: 6
                                    }}
                                    autoComplete="off"
                                />
                            </Item>
                        </Col>

                        {/* 性别 */}
                        <Col xs={24}>
                            <Item
                                name="userGender"
                                label={
                                    <span style={{display: 'flex', alignItems: 'center'}}>
                                        <TeamOutlined style={{marginRight: 6, color: '#1890ff'}}/>
                                        性别
                                    </span>
                                }
                            >
                                <Radio.Group
                                    options={[
                                        {value: 1, label: '男'},
                                        {value: 2, label: '女'}
                                    ]}
                                    optionType="button"
                                    buttonStyle="solid"
                                    style={{gap: 12}}
                                />
                            </Item>
                        </Col>

                        {/* 生日 - 修复的核心区域 */}
                        <Col xs={24}>
                            <Item
                                name="userBirthDate"
                                label={
                                    <span style={{display: 'flex', alignItems: 'center'}}>
                                        <CalendarOutlined style={{marginRight: 6, color: '#1890ff'}}/>
                                        生日
                                    </span>
                                }
                            >
                                <DatePicker
                                    placeholder="请选择您的生日"
                                    style={{
                                        width: '100%',
                                        height: 42,
                                        borderRadius: 6
                                    }}
                                    format="YYYY-MM-DD"
                                    allowClear
                                    // 添加点击事件处理函数，点击时清空值
                                    onClick={() => {
                                        form.setFieldValue('userBirthDate', null);
                                    }}
                                    // 确保值始终是moment对象或null
                                    onChange={(date) => {
                                        form.setFieldValue('userBirthDate', date);
                                    }}
                                    // 当值为null时不初始化moment对象
                                    initialValue={form.userBirthDate ? moment(form.userBirthDate) : null}
                                />
                            </Item>
                        </Col>

                        {/* 地址 */}
                        <Col xs={24}>
                            <Item
                                name="userAddress"
                                label={
                                    <span style={{display: 'flex', alignItems: 'center'}}>
                                        <HomeOutlined style={{marginRight: 6, color: '#1890ff'}}/>
                                        地址
                                    </span>
                                }
                            >
                                <Input
                                    placeholder="请输入您的地址"
                                    style={{
                                        height: 42,
                                        borderRadius: 6
                                    }}
                                    autoComplete="off"
                                />
                            </Item>
                        </Col>

                        {/* 简介 */}
                        <Col xs={24}>
                            <Item
                                name="userIntroduction"
                                label={
                                    <span style={{display: 'flex', alignItems: 'center'}}>
                                        <FileTextOutlined style={{marginRight: 6, color: '#1890ff'}}/>
                                        简介
                                    </span>
                                }
                            >
                                <TextArea
                                    placeholder="请输入个人简介（最多200字）"
                                    rows={4}
                                    maxLength={200}
                                    style={{borderRadius: 6}}
                                    showCount
                                    autoSize={{minRows: 2, maxRows: 4}}
                                />
                            </Item>
                        </Col>
                    </Row>
                </Form>
            </Card>
        </Modal>
    );
};

export default EditPersonalModal;